<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/6
 * Time: 14:41
 */

namespace app\api\model;


use app\admin\model\BydAddress;
use app\admin\model\BydDesigner;
use app\admin\model\BydDestri;
use app\admin\model\BydDispro;
use app\admin\model\BydDistri;
use app\admin\model\BydMyfollow;
use app\admin\model\BydShopCart;
use app\admin\model\BydShopCategory;
use app\admin\model\BydShopExpress;
use app\admin\model\BydShopMyfoot;
use app\admin\model\BydShopOrder;
use app\admin\model\BydShopPl;
use app\admin\model\BydShopPlhf;
use app\admin\model\BydUserSale;
use app\admin\model\BydVideo;
use app\api\controller\Wxpay;
use think\Model;
use think\Db;
//用户ID，快递鸟提供，注意保管，不要泄漏
defined('EBusinessID') or define('EBusinessID', '1739064');//即用户ID，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx
//API key，快递鸟提供，注意保管，不要泄漏
defined('ApiKey') or define('ApiKey', 'b3384764-7f8c-43f9-b39d-522a16c216ad');//即API key，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx
//请求url，正式地址
defined('ReqURL') or define('ReqURL', 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx');
class BydShop extends Model
{
// 表名
    protected $name = 'byd_shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    /**
     * 商城列表
     */
    public static function shopindex(){
        $arr=BydShop::where('tuijian',1)->where('switch',1)->select();//推荐且上架的商品
        if($arr){
            return $arr;
        }else{
            return null;
        }
    }
    /**
     * 商品分类
     */
    public static function category(){
       $catrgory=db('BydShopCategory')->where('switch',1)->order('sort desc')->select();

       $qq=BydShop::listToTree($catrgory);
      if($qq){
          return $qq;
      }else{
          return null;
      }
    }

    /**
     * [把返回的数据集转换成树形结构Tree]
     * @param array  $list 要转换的数据集
     * @param string $pid 父级ID键名
     * @param string $pk ID键名
     * @param string $child 子集键名
     * @param int    $root 一级菜单的parent_id 的值 （默认 0）
     * @return array
     */
    public static function listToTree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
    /**
     * 分类下产品
     */
    public static function categoryshop($data){
        if($data==31){
            $set=BydSet::select();
            if(!empty($set)){
                foreach ($set as &$v){
                    $v['shop']=BydShop::where('set',$v['id'])->field('id,name,simage,xc_price')->select();
                }
                return $set;
            }
        }elseif($data==32 || $data==33){
            $set=BydSet::where('category',$data)->select();
            if(!empty($set)){
                foreach ($set as &$v){
                    $v['shop']=BydShop::where('set',$v['id'])->field('id,name,simage,xc_price')->select();
                }
                return $set;
            }
        }
        $where['category']=$data;
        $where['switch']=1;
        $where['shoptage']=0;
        $find=BydShop::where($where)->paginate(100);
//        $find=db('BydShopCategory')->where('pid',$data)->select();//所有的二级分类
//        foreach ($find as &$v){
//            $v['shop']=BydShop::where($where)->paginate(10);
//        }
        if($find){
            return $find;
        }else{
            return null;
        }
    }
    /**
     * 商品详情
     */
   public static function shopxq($id){
       if($id['user_id']>0){
       $add=new BydShopMyfoot();
       $finffoot=$add->where('user_id',$id['user_id'])->where('shop_id',$id['id'])->find();
       if($finffoot){
           $fsave=$add->where('user_id',$id['user_id'])->where('shop_id',$id['id'])->update(['createtime'=>time()]);
       }else{
           $add->data([
               'user_id'  => $id['user_id'],
               'shop_id' => $id['id'],
           ]);
       }
       $add->save();
       }
       $find=BydShop::find($id['id']);
       $where['shopid']=$id['id'];
       $find['son']=db('BydShopSpecial')->where($where)->select();
       $find['follow']=db('BydMyfollow')->where('shop_id',$id['id'])->where('user_id',$id['user_id'])->find();
       $wheress['shop_id'] = $id['id'];
       $pl = db('BydShopPl')->where($wheress)->order('id desc')->find();//查询出这个帖子的所有评论

       if ($pl) {
           $wheree['id'] = $pl['user_id'];
           $usfind = db('BydUser')->where($wheree)->field('username,avatar')->find();//找到此条评论的用户新西
           if(!empty($usfind)){
               $pl['name'] = $usfind['username'];
               $pl['head'] = $usfind['avatar'];
           }
           $wh['pl_id'] = $pl['id'];
           $pl['list']=db('BydShopPlhf')->where($wh)->order('create_at desc')->find();//找到此条评论的回复
           if($pl['list']){
               $pl['list']['names'] = '官方';
               $q['bhhfuser'] = db('BydUser')->where('id', $pl['list']['pl_user_id'])->field('username,avatar')->find();//找到被回复人的信息
               $qqq= db('BydUser')->where('id', $pl['list']['user_id'])->field('username,avatar')->find();//找到回复人的信息
               $pl['list']['user']=$qqq;
           }
           $find['pll']=$pl;
       }else{
           $find['pll']='';
       }
       $arrs[]=$find;
       return $arrs;
   }
   /**
    * 商品评论
    */
    public static function pl($data)
    {
        $dataArray = explode(',',$data['shopid']);
        foreach ($dataArray as $vals){
            if($data['content']==null){
                $creat['image'] = $data['image'];
            }elseif($data['image']==null){
                $creat['content'] = $data['content'];
            }else{
                $creat['image'] = $data['image'];
                $creat['content'] = $data['content'];
            }
            $creat['shop_id'] =$vals;
            $creat['state']=$data['state'];
            $creat['user_id'] = $data['userid'];
            $pl = new BydShopPl();
            $arr = $pl->create($creat);
        }

        if ($arr) {
            $order=new BydShopOrder();
            if($data['state']==1){
                $save['state']=17;
            }else{
                $save['state']=4;
            }
            $wheree['orderid']=$data['orderid'];
            $xfscore=$order->isUpdate(true,($wheree))->save($save);
            return $arr;
            //$this->success(__('评论成功'), ['status' => $arr]);
        } else {
           return null;
        }
    }
    /**
     *   回复评论
     * @ApiMethod (POST)
     * @param integer $pl_id 评论的id
     * @param integer $pl_user_id 被回复人的id
     * @param integer $userid 用户的id
     * @param varchar $content 评价的内容
     */
    public static function hfpl($data)
    {
        $cerat['pl_id'] = $data['pl_id'];
        $cerat['pl_user_id'] = $data['pl_user_id'];
        $cerat['user_id'] = $data['userid'];
        $cerat['content'] = $data['content'];
        $pl = new BydShopPlhf();
        $arr = $pl->create($cerat);
        if ($arr) {
            return $arr;
        } else {
            return null;
        }
    }
    /**
     * 评论渲染
     */
    public static function allcomment($data)
    {
        $find = db('BydShop')->where('id','=',$data['shopid'])->find();//查询出这个帖子
        $wheres['shop_id']=$data['shopid'];

        $find['pl'] = db('BydShopPl')->where($wheres)->order('id desc')->select();//查询出这个帖子的所有评论

        if ($find['pl']) {
            //循环每一条评论
            foreach ($find['pl'] as $k => &$v) {
                $wheree['id'] = $v['user_id'];
                $usfind = db('BydUser')->where($wheree)->field('username,avatar')->find();//找到此条评论的用户新西
                $v['name'] = $usfind['username'];
                $v['head'] = $usfind['avatar'];
                $wh['pl_id'] = $v['id'];
                // $wh['pl_user_id'] = $v['user_id'];
                $v['tt']=db('BydShopPlhf')->where($wh)->order('create_at desc')->select();//找到此条评论的回复
                if($v['tt']){
                    foreach ($v['tt'] as &$q) {
                        $q['bhhfuser'] = db('BydUser')->where('id', $q['pl_user_id'])->field('username,avatar')->find();//找到被回复人的信息
                        $qqq= db('BydUser')->where('id', $q['user_id'])->field('username,avatar')->find();//找到回复人的信息
                        $q['user']=$qqq;
                    }
//$v['hf']=$rrs;
                }
            }
//            print_r($pl);die;
        }
        if ($find ) {
            return $find;
        } else {
            return null;
        }
    }

    /**
     * 商城模糊查询
     */
    public static function shoplike($data){
        $map['name'] = ['like', '%' . $data['name'] . '%'];
        $arr=BydShop::where($map)->select();
        if($arr){
            return $arr;
        } else {
          return null;
        }
    }
    /**
     * 购物车展示
     */
    public  function shopcart($data){
        $cart=BydShopCart::where('user_id',$data['id'])->select();
        if($cart){
            foreach ($cart as $v){
                $v['set']=BydSet::where('id',$v['setid'])->field('name')->find();
                $v['shop']=BydShop::find($v['shopid']);
            }
            return $cart;
        }else{
            return null;
        }
    }
    /**
     * 加入购物车
     */

    public static function addshopcart($data){
        $care=new BydShopCart();
        $shop=new BydShop();
        // $data['specid']=$arr;
        $where['user_id']=$data['user_id'];
        $where['shopid']=$data['shopid'];
        $where['specid']=$data['specid'];//规格id
        $where['specidsize']=$data['specidsize'];//规格详情
        $where['orderid']=$data['orderid'];
        $find=$care->where($where)->find();
        $shopfind=$shop->where('id',$data['shopid'])->find();
        $price=$data['price'];//现金价格
        if($find){
            //$saves=$care->where($where)->setInc('price',$price);
            $save=$care->where($where)->setInc('num',$data['num']);
        }else{
            $data['price']=$price;
            $save=BydShopCart::create($data);
        }
        if($save){
           return $save;
        } else {
          return null;
        }
    }
    /**
     * 购物车删除
     */
    public static function shopcaredeal($data){
        $deal=BydShopCart::destroy($data['id']);
        if($deal){
          return $deal;
        }else{
            return null;
        }
    }
    /**
     * 添加我的足迹
     */
    public static function myfoot($data){
        $add=new BydShopMyfoot();
        $add->data([
            'user_id'  => $data['user_id'],
            'shop_id' => $data['shop_id'],
        ]);
        $add->save();
        if($add){
            return $add;
        }else{
            return null;
        }
    }
    /**
     * 我的足迹渲染

     */
    public  static function myfootxr($data){
        $time=BydShop::getDayTs($data['time']);
        $arr=Db('byd_shop_myfoot')->where('createtime', 'between time', [$time['beginDay_ts'],$time['endDay_ts']])->where('user_id','=',$data['user_id'])->order('updatetime desc')->paginate($data['limit']);
        if($arr){
            $qq=[];
            foreach ($arr as $k=>$v){
                $v['content']=BydShop::where('id',$v['shop_id'])->find();
                $qq[$k]=$v;
            }
            //$arr['content']=$conten;
            return $qq;
        }else{
            return null;
        }

    }

    /**
     * 计算某一时间的开始时间
     */
    public  static function getDayTs($time_ts){
        //比如$time_ts=1571706109
        $date_day=date('Y-m-d',$time_ts);//"2019-10-22"
        $beginDay_ts=strtotime($date_day);//1571673600
        //86400=24*60*60，【86400 - 1 ==> 23:59:59 】
        $endDay_ts=$beginDay_ts+86400-1;
        $day_ts=[];
        $day_ts['beginDay_ts']=$beginDay_ts;
        $day_ts['endDay_ts']=$endDay_ts;
        //dd($day_ts);
        return $day_ts;
    }
    /**
     * 添加收藏
     */
    public  static function addfollow($data){
        if($data['state']==0){
            $add=new BydMyfollow();
            $add->data([
                'user_id'  => $data['user_id'],
                'type' => $data['type'],
                'shop_id' => $data['shop_id'],
                'video_id' => $data['video_id']
            ]);
            $add->save();
        }else{
            if($data['type']==1){
                $add=BydMyfollow::where('user_id',$data['user_id'])->where('video_id',$data['video_id'])->delete();
            }else{
                $add=BydMyfollow::where('user_id',$data['user_id'])->where('shop_id',$data['shop_id'])->delete();
            }

        }

        if($add){
            return $add;
        }else{
            return null;
        }
    }
    /**
     * 我的收藏
     */
    public static function lookfollow($data)
    {
        $arr = BydMyfollow::where('user_id', $data['user_id'])->where('type', $data['type'])->paginate(10);
        if ($arr) {
            if ($data['type'] == 1) {
                foreach ($arr as $v) {
                    $v['content'] = BydVideo::where('id', $v['video_id'])->find();
                }
            } else {
                foreach ($arr as $v) {
                    $v['content'] = BydShop::where('id', $v['shop_id'])->find();
                }
            }
            return $arr;
        } else {
            return null;
        }

    }
    // xml转成数组
    private function FromXml( $xml ) {
        if(!$xml){
            return ['code'=>400,'msg'=>'xml数据异常'];
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }
    /**
     * 购物车立即支付/放弃支付
     * user_id 用户id
     *  cartid 购物车id
     * num 商品数量
     * addressid 地址的id
     * type 0为立即支付1为放弃支付
     * specidsize 商品规格详情
     */
    public function cartpay(){

        $data = $this->request->request('');
        $osn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);//订单号
        $user=BydUser::where( 'id',$data['user_id'])->find();
        $address=BydAddress::where('id',$data['addressid'])->find();//查询出地址
        $uu=new BydUser();
        if($data['type']==0){
            $data['state']=1;//立即支付
        }else{
            $data['state']=0;//放弃支付
        }
       // $bl=\app\admin\controller\BydShopOrder::find();
        if($data['cartid']==0){
            $add = new BydShopOrder();
            $add->data([
                'orderid'  => $osn,
                'user_id'  => $data['user_id'],
                'state' =>  $data['state'],
                'productid' =>  $data['shopid'],
                'num' =>   $data['num'],
                'price' =>  $data['price'],
                'addressid' =>   $data['addressid'],
                'address' =>   $address['title'],
                'addressxq' =>   $address['address'],
                'phone' =>   $address['phone'],
                'special' =>   $data['specid'],
                'specidsize' => $data['specidsize'],
            ]);
            $add->save();
          if($add){

              //微信支付
              $wxpay=new Wxpay();

              $arr = [
                  'user_id'=>$data['user_id'],
                  'orderid'  => $osn,
                  'openid' => $user['openid'],
                  'status'=>1
              ];
              $pay=$wxpay->pay($arr);
              print_r($pay);die;
     return json(['code'=>1,'msg'=>'请求成功','data'=>$pay]);

          }
        }else{
            $cart=BydShopCart::where('id','in',$data['cartid'])->select();
            $add = new BydShopOrder();
//            foreach ($cart as $v){
                $add->data([
                    'orderid'  => $osn,
                    'user_id'  => $data['user_id'],
                    'state' =>  $data['state'],
                    'productid' =>  $cart['shopid'],
                    'num' =>   $cart['num'],
                    'jfprice' =>  $cart['jfprice']*$cart['num'],
                    'price' =>   $cart['price']*$cart['num'],
                    'addressid' =>   $data['addressid'],
                    'address' =>   $address['title'],

                    'special' =>   $cart['specid'],
                    'specidsize' => $cart['specidsize'],
                ]);
                $add->save();
                $save['xfscore']=$user['xfscore']-$cart['jfprice'];
                $wheree['id']=$data['user_id'];
                $xfscore=$uu->isUpdate(true,($wheree))->save($save);
                $deal=BydShopCart::destroy($cart['id']);//删除购物车里面的数据
//            }
        }
        if($add && $data['type']==0){
            $this->success(__('支付成功'));
        }elseif($add){
            $this->success(__('请求成功'));
        }else{
            $this->error(__('请求失败'));
        }
    }
    /**
     * 待支付---确认支付
     * id 订单的id
     */
    public function orderpay(){
        $data = $this->request->request('');
        //$ww['id']=$data['id'];
        $order=new BydShopOrder();
        $ww['id']=$data['id'];
        $deal=$order->isUpdate(true,$ww)->save(['state'=>1]);
        if($deal){
            return $deal;
        }else{
            return null;
        }
    }
    /**
     * 待支付---取消订单
     * id 订单的id
     */
    public function orederdzf(){
        $data = $this->request->request('');
        //$ww['id']=$data['id'];
        $deal=BydShopOrder::destroy($data['id']);
        if($deal){
            return $deal;
        }else{
            return null;
        }
    }
    /**
     * 待支付--修改地址
     * id  订单id
     * addressid 地址id
     */
    public function editaddress(){
        $data = $this->request->request('');
        $user = BydShopOrder::get($data['id']);
        $user->addressid     =$data['addressid'];
        $user->save();
        if($user){
            return $user;
        }else{
            return null;
        }
    }
    /**
     * 带收货--确认收货
     */
    public function sureorder($data){

//        $user = BydShopOrder::get($data['id']);
//        $user->state     =3;
//        $user->save();
        //支付定金过后
           $user=BydShopOrder::where('id',$data['id'])->find();
           if($user['score']==0){
               $state=3;
           }else{
               $state=4;
           }
           $uporder=BydShopOrder::where('id',$data['id'])->update(['state'=>$state]);
        if($uporder){
            $this->success(__('修改成功'));
        }else{
            $this->error('修改失败');
        }
    }
    /**
     * 销售员订单分佣
     * id
     */
    public static function ordersub($data){
        $order=BydShopOrder::find($data['id']);
        $dis=BydDistri::find($order['user_id']);//查找此用户的上级
        $findtwo=BydUserSale::find($dis['pid']);
        if($findtwo['level']==2){
            //b1直接分佣
            $dispro=BydIdentity::find(2);
            $bl=$dispro['myproduct']/100;
            $money=$order['price']*$bl;
            $add = new BydDispro();
            $add->data([
                'pid'  => $dis['pid'],
                'state' =>  1,
                'user_id' =>  $order['user_id'],
                'type' => 0,
                'order_id'=>$order['orderid'],
                'money'=>0,
                'price'=>$money
            ]);
            $add->save();
        }else{
            //上级为bs分佣8%
            $dispro=BydIdentity::find(1);
            $bl=$dispro['myproduct']/100;
            $money=$order['price']*$bl;
            $add = new BydDispro();
            $add->data([
                'pid'  => $dis['pid'],
                'state' =>  1,
                'user_id' =>  $order['user_id'],
                'type' => 0,
                'order_id'=>$order['orderid'],
                'money'=>0,
                'price'=>$money
            ]);
            $add->save();
            //b1分佣20%
            $bb=BydUserSale::where('user_id',$dis['family'])->find();//查找此用户的上级
            if($bb['level']==2){
                $dispro=BydIdentity::find(2);
                $bl=$dispro['sonproduct']/100;
                $money=$order['price']*$bl;
                $add = new BydDispro();
                $add->data([
                    'pid'  => $dis['pid'],
                    'state' =>  1,
                    'user_id' =>  $order['user_id'],
                    'type' => 0,
                    'order_id'=>$order['orderid'],
                    'money'=>0,
                    'price'=>$money
                ]);
                $add->save();
            }
        }
    }
    /**
     * 设计师方案分佣
     * id  订单id
     */
    public function desfy($data){
        $order=BydShopOrder::find($data['id']);//查找订单
        $dis=BydDistri::find($order['user_id']);//查找此用户的上级
        $findtwo=BydDesigner::where('user_id',$dis['pid'])->find($dis['pid']);
        if($findtwo['level']==4){
            //b1直接分佣
            $dispro=BydIdentity::find(4);
            $bl=$dispro['myproduct']/100;
            $money=$order['price']*$bl;
            $add = new BydDispro();
            $add->data([
                'pid'  => $dis['pid'],
                'state' =>  1,
                'user_id' =>  $order['user_id'],
                'type' => 0,
                'order_id'=>$order['orderid'],
                'money'=>0,
                'price'=>$money
            ]);
            $add->save();
        }else{
            //上级为bs分佣8%
            $dispro=BydIdentity::find(3);
            $bl=$dispro['myproduct']/100;
            $money=$order['price']*$bl;
            $add = new BydDispro();
            $add->data([
                'pid'  => $dis['pid'],
                'state' =>  1,
                'user_id' =>  $order['user_id'],
                'type' => 0,
                'order_id'=>$order['orderid'],
                'money'=>0,
                'price'=>$money
            ]);
            $add->save();
            //b1分佣20%
            $bb=BydDesigner::where('user_id',$dis['family'])->find();//查找此用户的上级
            if($bb['level']==4){
                $dispro=BydIdentity::find(2);
                $bl=$dispro['sonproduct']/100;
                $money=$order['price']*$bl;
                $add = new BydDispro();
                $add->data([
                    'pid'  => $dis['pid'],
                    'state' =>  1,
                    'user_id' =>  $order['user_id'],
                    'type' => 0,
                    'order_id'=>$order['orderid'],
                    'money'=>0,
                    'price'=>$money
                ]);
                $add->save();
            }
        }
    }
    /**
     * 获取accesstoken
     */
    public function getAccessToken()
    {
        $appId = 'wx00e9e5b843259a9d';
        $secretId ='5a47f8a3b97773614c77da7900a896a3';
        $accessUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';
        // $url = sprintf($accessUrl,$appId,$secretId);
        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx00e9e5b843259a9d&secret=5a47f8a3b97773614c77da7900a896a3';
        //print_r($url);die;
        $result =$this->https_request($url);
        //$result = $this->https_request($url);
        $Result = json_decode($result, true);
        return $Result['access_token'];
        // return $Result;

    }
    #curl请求
public function https_request($url,$data = null){
        if(function_exists('curl_init')){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION,1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
    /**
     * 生成个人专属二维码
     * id  用户id
     * level 身份
     */
    public function ewm($data){

        //调用get_qrcode方法，获取二维码图片
        if($data['id']){
            $base64_img = $this->get_qrcode($data['id'],$data['level'],$data['type']);
//调用base64_save方法，将图片保存到指定位置，并获取图片新名称
            $new_name = $this->base64_save($base64_img,'./uploads/');
            $path='https://bao.scwushen.com/uploads/'.$new_name;
            $paths=stripslashes($path);
if($data['type']==0){
    $user = new BydUser();
// save方法第二个参数为更新条件
    $user->save([
        'bewm' => $paths,
    ],['id' => $data['id']]);
}else{
    $user = new BydUser();
// save方法第二个参数为更新条件
    $user->save([
        'dewm' => $paths,
    ],['id' => $data['id']]);

}
return $paths;
//            $where['id']=$data['id'];
//re
//            $save=$user->isUpdate(true,$where)->save(['ewm'=>$paths]);
            $this->success(__('请求成功'), ['status' => $paths]);
        }else{
            return null;
            $this->error(__('请登录'));
        }

    }
    //生成二维码
    function get_qrcode($id,$level,$type){
        //$type 0:b端1:d端
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $ACCESS_TOKEN = $this->getAccessToken();
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        $param = json_encode(array("path"=>"pages/Home/start?uid=$id&level=$level&type=$type","width"=>150));
        //$param = json_encode(array("path"=>"/pages/pagesC/Shopping?uid=$id&level=$level&shopid=72","width"=>150));
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");

        //生成二维码
        // file_put_contents("qrcode.png", $result);
        $base64_image = "data:image/jpeg;base64,".base64_encode( $result );

        return $base64_image; //返回base64图片数据
    }
    /*
        * 保存base64格式图片到指定文件夹中
        * $base64_img 图片数据
        * $path 要保存到的图片地址
        */
    function base64_save($base64_img,$path){
        $img_base = str_replace('data:image/jpeg;base64,', '', $base64_img);
        $img_name = time().rand(1000,9999).'.jpg'; //图片新名称
        $img_path = $path.$img_name;
        file_put_contents($img_path,base64_decode($img_base));

        return $img_name; //返回新名称
    }

    public static function express($com,$num){
        //参数设置
        $key = 'aekLGcMH9130';                        //客户授权key
        $customer = '74373F759E35A098E1A38DD708BED9BD';                   //查询公司编号
        $param = array (
            'com' => $com,             //快递公司编码shunfeng
            'num' =>$num,             //快递单号SF6091155310867
            'phone' => '',                //手机号
            'from' => '',                 //出发地城市
            'to' => '',                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = json_decode($result);
        $arr=json_decode(json_encode($data),true);
        return $arr;
    }
    //把请求发送到微信服务器换取二维码
    function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST'){
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != ''){
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    /**
     * 查看物流
     *  id 订单id
     */
    public static function lookexpress($data){

        $order=BydShopOrder::find($data['id']);
        $express=BydShopExpress::find($order['express']);
        $arr=BydShop::express($express['order'],$order['expressorder']);
        $arr['conpany']=$express;

        if($arr){
            return $arr;
        } else {
            return null;
        }
    }
//封装提现方法
    function tixian($money){
        $appid = "wx00e9e5b843259a9d";//商户账号appid
        $secret = "##########";//api密码
        $mch_id = "1584376091";//商户号
        $mch_no = "#######";
        $openid="obdeX4v1JCIJdH45QhyJNZnHusBs";//授权用户openid

        $arr = array();
        $arr['mch_appid'] = $appid;
        $arr['mchid'] = $mch_id;
        $arr['nonce_str'] = $this->getRandChar(32);//随机字符串，不长于32位
        $arr['partner_trade_no'] = '1298016501' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);//商户订单号
        $arr['openid'] = $openid;
        $arr['check_name'] = 'NO_CHECK';//是否验证用户真实姓名，这里不验证
        $arr['amount'] = 0.01;//付款金额，单位为分
        $desc = "###提现";
        $arr['desc'] = $desc;//描述信息
        $arr['spbill_create_ip'] = '192.168.0.1';//获取服务器的ip
        //封装的关于签名的算法
        //$notify = new Notify_pub();
        //$notify->weixin_app_config = array();
        //$notify->weixin_app_config['KEY'] = $mch_no;

        $arr['sign'] = $this->Sign($arr);//签名

        $var = $this->arrayToXml($arr);
        $xml = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', $var, 30, array(), 1);
        $rdata = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        print_r($rdata);die;
        $return_code = (string)$rdata->return_code;
        $result_code = (string)$rdata->result_code;
        $return_code = trim(strtoupper($return_code));
        $result_code = trim(strtoupper($result_code));

        if ($return_code == 'SUCCESS' && $result_code == 'SUCCESS') {
            $isrr = array(
                'con'=>'ok',
                'error' => 0,
            );
        } else {
            $returnmsg = (string)$rdata->return_msg;
            $isrr = array(
                'error' => 1,
                'errmsg' => $returnmsg,
            );

        }
        return json_encode($isrr);
    }
//上个方法中用到的curl_post_ssl()
    function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
    {
        $isdir = "/cert/";//证书位置

        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
        curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
        curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
        curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
        curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);//全部数据使用HTTP协议中的"POST"操作来发送

        $data = curl_exec($ch);//执行回话
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
//遍历数组方法
    function arraytoxml($data){
        $str='<xml>';
        foreach($data as $k=>$v) {
            $str.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $str.='</xml>';
        return $str;
    }
    //生成签名
    public function sign($Obj)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[strtolower($k)] = $v;
        }
        // 签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = self::formatBizQueryParaMap($Parameters, false);
        // 签名步骤二：在string后加入KEY
        $String = $String . "&key=" . 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M';
        // 签名步骤三：MD5加密
        $result_ = strtoupper(md5($String));
        return $result_;
    }
    // 将数组转成uri字符串
    protected function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    public function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
// 微信提现转账
    function transfer($data){
        $appid = "wx00e9e5b843259a9d";//商户账号appid
        $secret = "##########";//api密码
        $mch_id = "1584376091";//商户号
        header("Content-type: text/html; charset=utf-8");
        //CA证书及支付信息
        $wxchat['appid'] = "wx00e9e5b843259a9d";
        $wxchat['mchid'] = "1584376091";

        $wxchat['api_cert'] = EXTEND_PATH.'/apiclient_cert.pem';
        $wxchat['api_key'] = EXTEND_PATH.'/apiclient_key.pem';

        // $wxchat['api_ca'] = '/plugins/payment/weixin/cert/rootca.pem';
        $webdata = array(
            'mch_appid' => $wxchat['appid'],
            'mchid'     => $wxchat['mchid'],
            'nonce_str' => md5(time()),
            //'device_info' => '1000',
            'partner_trade_no'=> '2021054874', //商户订单号，需要唯一
            'openid' => "obdeX4v1JCIJdH45QhyJNZnHusBs",//转账用户的openid
            'check_name'=> 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK：强制 NO_CHECK：
            //'re_user_name' => 'jorsh', //收款人用户姓名
            'amount' => 1 * 100, //付款金额单位为分
            'desc'   => 'YH提现',
            'spbill_create_ip' => request()->ip(),
        );

        foreach ($webdata as $k => $v) {
            $tarr[] =$k.'='.$v;
        }

        sort($tarr);
       // $sign = implode($tarr, '&');
//        $sign .= '&key='.WxPayConfig::$key;
       // $webdata['sign']=strtoupper(md5($sign));
        $webdata['sign'] = $this->Sign($webdata);//签名
        $wget = $this->array2xml($webdata);

        $pay_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        $res = $this->http_post($pay_url, $wget, $wxchat);

        if(!$res){
            return array('status'=>1, 'msg'=>"Can't connect the server" );
        }
        $content = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);

        if(strval($content->return_code) == 'FAIL'){
            return array('status'=>1, 'msg'=>strval($content->return_msg));
        }
        if(strval($content->result_code) == 'FAIL'){
            return array('status'=>1, 'msg'=>strval($content->err_code),':'.strval($content->err_code_des));
        }

        $rdata = array(
            'mch_appid'        => strval($content->mch_appid),
            'mchid'            => strval($content->mchid),
            'device_info'      => strval($content->device_info),
            'nonce_str'        => strval($content->nonce_str),
            'result_code'      => strval($content->result_code),
            'partner_trade_no' => strval($content->partner_trade_no),
            'payment_no'       => strval($content->payment_no),
            'payment_time'     => strval($content->payment_time),
        );
        return $rdata;

    }
    /**
     * 将一个数组转换为 XML 结构的字符串
     * @param array $arr 要转换的数组
     * @param int $level 节点层级, 1 为 Root.
     * @return string XML 结构的字符串
     */
    function array2xml($arr, $level = 1) {
        $s = $level == 1 ? "<xml>" : '';
        foreach($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value['TagName']);
            }
            if(!is_array($value)) {
                $s .= "<{$tagname}>".(!is_numeric($value) ? '<![CDATA[' : '').$value.(!is_numeric($value) ? ']]>' : '')."</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
        return $level == 1 ? $s."</xml>" : $s;
    }


    function http_post($url, $param, $wxchat) {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        if($wxchat){
            curl_setopt($oCurl,CURLOPT_SSLCERT,$wxchat['api_cert']);
            curl_setopt($oCurl,CURLOPT_SSLKEY,$wxchat['api_key']);

        }
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }








}